//
//  ArticleListVC.swift
//  HengYouCai
//
//  Created by lwj on 2017/11/30.
//  Copyright © 2017年 lwj. All rights reserved.
//  公告中心--代码

import UIKit

class ArticleListVCCell: UITableViewCell {
    
    //配置cell
    func configurationCell(_ modelTemp: ArticleModel) {
        self.contentLab.text = modelTemp.articleTitle
        self.timeLab.text = modelTemp.createTime
        
        self.redPoint.isHidden = !(modelTemp.artNoRead == "1")
    }
    //快捷生成cell
    static func wl_createCellWithTableView(_ tableView: UITableView) -> ArticleListVCCell {
        
        let cellID =
            NSStringFromClass(ArticleListVCCell.self);
        if let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as? ArticleListVCCell {
            return cell
        }else{
            return ArticleListVCCell(style: .default, reuseIdentifier: cellID)
        }
    }
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        
        self.addSubview(contentLab)
        _ = contentLab.sd_layout()
            .topSpaceToView(self,15)?
            .leftSpaceToView(self,15)?
            .autoWidthRatio(1)?
            .autoHeightRatio(0)
        contentLab.setSingleLineAutoResizeWithMaxWidth(JCWSCREENW-50)
        contentLab.setMaxNumberOfLinesToShow(0)
        self.addSubview(redPoint)
        _ = redPoint.sd_layout()
            .leftSpaceToView(contentLab,2)?
            .topSpaceToView(self,15)?
            .widthIs(4)?
            .heightIs(4)
        self.addSubview(timeLab)
        _ = timeLab.sd_layout()
            .topSpaceToView(contentLab,10)?
            .leftSpaceToView(self,15)?
            .autoWidthRatio(1)
        timeLab.setSingleLineAutoResizeWithMaxWidth(JCWSCREENW-50)
        self.addSubview(rowImgView)
        _ = rowImgView.sd_layout()
            .centerYEqualToView(self)?
            .rightSpaceToView(self,15)?
            .heightIs(14)?
            .widthIs(9)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    /// 内容
    lazy var contentLab: UILabel = {
        let temp = UILabel()
        temp.textColor = Normal_333Color
        temp.font = Font_WL(14)
        temp.textAlignment = .left
        return temp
    }()
    /// 时间
    lazy var timeLab: UILabel = {
        let temp = UILabel()
        temp.textColor = Normal_999Color
        temp.font = Font_WL(12)
        temp.textAlignment = .left
        return temp
    }()
    /// 右边的箭头
    lazy var rowImgView : UIImageView = {
        
        let temp = UIImageView()
        temp.image = UIImage(named: "right")
        
        return temp
    }()
    /// 小红点
    lazy var redPoint: UIView = {
        let temp = UIView()
        temp.backgroundColor = Normal_RedColor
        temp.layer.cornerRadius = 2
        temp.clipsToBounds = true
        return temp
    }()
}

class ArticleListVC: BaseTableViewController {

    //标题
    var titleName:String?
    
    var totalArr = Array<Any>()
    ///上拉下拉刷新管理器
    let  pageManager = JCWRefreshPageManager()
    override func viewDidLoad() {
        super.viewDidLoad()

        let footerView = UIView()
        footerView.backgroundColor = Normal_458Color
        self.tableView.tableFooterView = footerView
        self.navigationItem.title = self.titleName  //"公告中心"
        self.view.backgroundColor = Normal_458Color
        weak var weakSelf = self
        self.tableView.mj_header = LWRefreshGifHeader(refreshingBlock: {
            weakSelf?.pageManager.pageNo = JCWLimitNumberStarPage
            weakSelf?.loadData()
        })
        self.view.jcw_showGifLoading()
        loadData()
        
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tableView.reloadData()
    }
    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.pageManager.dataArr.count
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 75
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = ArticleListVCCell.wl_createCellWithTableView(tableView)
        cell.configurationCell(self.pageManager.dataArr[indexPath.row] as! ArticleModel)
        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = pageManager.dataArr[indexPath.row] as! ArticleModel
        model.artNoRead = "2"
        let webVC = BannerWebViewVC(urlStr: model.hotUrl, title: "公告中心")
        self.navigationController?.pushViewController(webVC!, animated: true)
        
    }

}

extension ArticleListVC {
    func loadData() {
        HYCNetService.hotspotMallHotspot(withDict: ["pageNo":self.pageManager.pageNo,"pageSize":JCWLimitNumberPageSize], onSuccess: { (result) in
            //
            
            debugPrint(self.pageManager.pageNo)
            //隐藏加载框
            self.view.hideHUDLoading(0)
            
            //坑 一定记得加可选值 否则 footer可能不存在
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            
//            let jsonResult = JSON(result as Any)
            let resultList: [Any]? = JSON(result as Any).dictionaryValue["articleList"]?.arrayObject

//            let resultList: [ArticleModel]? = ArticleModel.mj_objectArray(withKeyValuesArray:jsonResult["articleList"]) as? [ArticleModel]
//            let resultList: [Any]? = JSON(result as Any).dictionaryValue["articleList"]?.arrayObject
            if self.pageManager.pageNo == JCWLimitNumberStarPage {
                self.pageManager.dataArr.removeAll()
               
            }
            if let count = resultList?.count, count >= JCWLimitNumberPageSize{
                self.pageManager.pageNo += JCWLimitNumberStarPage
                weak var weakSelf = self
                self.tableView.mj_footer = JCWRefreshFooter(refreshingBlock: {
                    weakSelf?.loadData()
                })
            }else{
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            }
            self.pageManager.dataArr.append(contentsOf: ArticleModel.mj_objectArray(withKeyValuesArray: resultList))
            
            
            
            self.tableView.reloadData()
            
        }) { (code, errorMsg) in
            //
            //隐藏加载框
            self.view.hideHUDLoading(0)
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            self.view.showHUDFailTips(errorMsg, hideDelay: 1.5)
        }
    }
}
